﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using System.Drawing;
using RegisterationCommon.Common;

namespace RegisterationSystem.SyncService
{
    /// <summary>
    /// GetVerifiCode 的摘要说明
    /// </summary>
    public class GetVerifiCode : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            //清除页面缓存
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.Expires = 0;
            HttpContext.Current.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
            HttpContext.Current.Response.AddHeader("pragma", "no-cache");
            HttpContext.Current.Response.AddHeader("cache-control", "private");
            HttpContext.Current.Response.CacheControl = "no-cache";

            // 产生随机验证码字符
            string checkCode = BaseLibrary.GetRandomCode(4, ERandomCodeType.Both);
            //将字符串保存到Session中
            context.Session["RBVerifiCode"] = checkCode;
            System.Drawing.Bitmap img = new System.Drawing.Bitmap(68, 20);
            Graphics g = Graphics.FromImage(img);
            try
            {
                //随机码生成器
                Random random = new Random();

                //清空图片背景色
                g.Clear(Color.White);

                // 画图片的背景噪音线
                int i;
                for (i = 0; i < 25; i++)
                {
                    int x1 = random.Next(img.Width);
                    int x2 = random.Next(img.Width);
                    int y1 = random.Next(img.Height);
                    int y2 = random.Next(img.Height);
                    g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                }

                //设置字体
                Font font = new System.Drawing.Font("Arial", 14, (System.Drawing.FontStyle.Bold));
                System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, img.Width, img.Height), Color.Blue, Color.DarkRed, 1.2F, true);
                g.DrawString(checkCode, font, brush, 0, 0);

                //画图片的前景噪音点
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, img.Width - 1, img.Height - 1);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                img.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                context.Response.ClearContent();
                context.Response.ContentType = "image/Gif";
                context.Response.BinaryWrite(ms.ToArray());
            }
            finally
            {
                g.Dispose();
                img.Dispose();
            }
        }

        /// <summary>
        /// 内容是否仅一次使用
        /// </summary>
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}